package club.zykeji.ddns.zyddnsclientjava.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * Create by 丶TheEnd on 2020/5/5.
 * @author TheEnd
 */
@Component
public class HttpUtil {

    @Value("${ddns.server.host}")
    private String serverHost;

    @Value("${ddns.host}")
    private String host;

    /**
     * 获取当前本机IP
     * @return
     */
    public String getNativeIp() {
        String result = new RestTemplate().getForObject(serverHost + "/d-dns/ip/my", String.class);
        return getResultValue(result);
    }

    /**
     * 获取当前解析的IP
     * @return
     */
    public String getCurrentIp() {
        String url = serverHost + "/d-dns/dns/bind/current?host=" + host;
        String result = new RestTemplate().getForObject(url, String.class);
        return getResultValue(result);
    }

    /**
     * 更新IP解析
     * @param nativeIp
     * @return
     */
    public boolean updateIp(String nativeIp) {
        String url = serverHost + "/d-dns/dns/bind?host={}&value={}";
        String result = new RestTemplate().getForObject(StrUtil.format(url, host, nativeIp), String.class);
        String resultValue = getResultValue(result);
        return "success".equals(resultValue);
    }

    /**
     * 解析并获取服务端相应的msg数据
     * @param result
     * @return
     */
    private String getResultValue(String result) {
        JSONObject jsonObject = JSON.parseObject(result);
        Integer code = jsonObject.getInteger("code");
        if (code == null || !code.equals(200)) {
            return null;
        }
        return jsonObject.getString("msg");
    }

}
